/**
 * @author helio
 */
var DragOrderView = Ext.extend(BasicPanel,{
	
	initlize : function() {
		
		if(!this.corePanel) {
			
			this.detailsStore = new Ext.data.Store({
			    proxy: new Ext.data.MemoryProxy(this.detailsJson),
			    reader: new Ext.data.JsonReader({
					root: 'products',
			        fields: ['pid', 'pcode','pname', 'punit', 'sname',{name:'snumber', type:'float'}, 'pimageurl', {name:'buy_price', type:'float'},'specs','model']
			    }),
				sortInfo:{field: 'pcode', direction: 'ASC'}
			});
			
			// create the grid
			var csm = new Ext.grid.CheckboxSelectionModel();
			
			this.detailsGrid = new Ext.grid.GridPanel({
				store: this.detailsStore,
				columns: [csm,{
					header: "商品编号",
					dataIndex: 'pcode',
					width: 60,
					sortable: true
				}, {
					header: "商品名称",
					dataIndex: 'pname',
					sortable: true
				}, {
					header: "规格",
					dataIndex: 'specs',
					sortable: true
				}, {
					header: "型号",
					dataIndex: 'model',
					sortable: true
				}, {
					header: "采购价格",
					dataIndex: 'buy_price',			
					width: 60,
					align: 'right',
					//renderer: SALE.Utils.stockRenderer.createDelegate(this),
					sortable: true,
					
					editor: new Ext.form.NumberField({
						allowBlank: true
					})					
				}, /*{
					header: "仓库",
					dataIndex: 'sname',			
					width: 60,
					sortable: true
				}, */{
					header: "在库数量",
					dataIndex: 'snumber',			
					width: 60,
					align: 'right',
					renderer: SALE.Utils.stockRenderer.createDelegate(this),
					sortable: true
				}],
				
				sm: csm,
				
				title: '商品采购...',
				
				tbar:[new Ext.form.ComboBox({
					id: 'oquerytype',
					tpl: comboxTpl,
				    triggerAction: 'all',
				    lazyRender:true,
				    forceSelection:true,
                 	selectOnFocus: true,
				    mode: 'local',
				    width: 100,
				    store: new Ext.data.ArrayStore({
				        id: 0,
				        fields: [
				            'code',
				            'name'
				        ],
				        data: [[1, '按编号查询'], [2, '按名称查询']]
				    }),
				    valueField: 'code',
				    displayField: 'name',
				    value:2
				}), '-', {
					id: 'oqueryvalue',
                	xtype:'trigger',
                    triggerClass: 'x-form-search-trigger',
                    width: 200,
                    onTriggerClick: this.queryStocksProducts.createDelegate(this),
                    listeners: {
        				'show': this.queryStocksProducts.createDelegate(this)
        			}
                }],
				
				viewConfig: {
			        forceFit: true,
					enableRowBody:true,
		            showPreview:true
			    },
		
				loadMask: true,
				stripeRows: true,
				border: true,
				autoExpandColumn: 'name',
				layout: 'fit',
				enableDragDrop: true,
				ddGroup: 'addItemDDGroup',
				region: 'center'
			});
			
			this.itemsStore = new Ext.data.JsonStore({
				proxy: new Ext.data.MemoryProxy(null),
			    reader: new Ext.data.JsonReader({
					root: 'items',
					remoteSort: true,
			        fields: ['pcode','pname', {name:'pnumber', type:'float'}, {name:'pprice', type:'float'}, {name:'pamount', type:'float'}]
			    }),
				sortInfo:{field: 'pname', direction: 'ASC'}
			});
			this.itemsStore.load();

			this.saleItemView = new Ext.DataView({
				tpl: saleItemTemplate,
				singleSelect: true,
				overClass:'x-view-over',
				itemSelector: 'div.item-info',
				emptyText : '<div style="padding:10px;"></div>',
				store: this.itemsStore,
				listeners: {
					'dblclick'       : {fn:this.showModifyItemWin, scope:this},
					'beforeselect'   : {fn:function(view){
				        return view.store.getRange().length > 0;
				    }}
				},
				prepareData: this.amountFormatData.createDelegate(this)
			});
			
			this.salePanel = new Ext.Panel({
				id: 'sale-items-view',
				region: 'east',
				title: '采购单',
				split: true,
				collapsible: true,
				autoScroll: true,
				layout: 'fit',
			    width: 208,
			    minSize: 100,
			    maxSize: 300,
			    
			    items: this.saleItemView,
				
				tbar:['->',{
					text:'保存',
		            tooltip:'保存',
		            iconCls:'save',
					handler: this.savePurchaseOrder.createDelegate(this)
		        }, '-', {
		            text:'预览',
		            tooltip:'预览',
		            iconCls:'option',
					handler: this.viewPurchaseOrder.createDelegate(this)
		        },'-',{
		        	text:'清空',
		            tooltip:'清空',
		            iconCls:'erase',
					handler: this.clearItems.createDelegate(this)
		        }],
				
			    listeners: {
					afterrender : function(obj,evt) {
						var secondGridDropTarget = new Ext.dd.DropTarget(obj.body.dom, {
			                ddGroup    : 'addItemDDGroup',
			                notifyDrop : this.showDetails.createDelegate(this)
						});
					}.createDelegate(this)
				}
			});
			
			this.corePanel = {
	            layout: 'border',
	            border: false,
	            items: [this.detailsGrid, this.salePanel]
			}
			
		}
	},
	
	initlizeDataHandler : function(resultJson) {
		this.detailsJson['products'] = resultJson.products;
		this.detailsStore.load({params:{start:0, limit:25}});
	},
	
	getCorePanel : function() {
		if (!this.corePanel) {
			this.initlize();
			SALE.Action.getProductsSaleListJson(this.initlizeDataHandler.createDelegate(this));
		}
		return this.corePanel;
	},
	
	queryStocksProducts : function() {
		var querytype = Ext.getCmp('oquerytype').getValue();
		var queryvalue = Ext.getCmp('oqueryvalue').getValue();
		var condition = {};
		if(querytype == 1) {
			condition.code = queryvalue;
		} else if(querytype == 2) {
			condition.name = queryvalue;
		} 
		
		if(queryvalue){
			SALE.Action.getProductsSaleListJson(this.initlizeDataHandler.createDelegate(this), condition);
		}
	},
	
	amountFormatData: function(data) {
		data.pamount = parseFloat(data.pnumber)*parseFloat(data.pprice);
    	return data;
	},
	
	showDetails : function(ddSource){
	    var records =  ddSource.dragData.selections;
        Ext.each(records, function(record){
        	
        	var items = this.itemsStore.getRange();
        	var existed = false;
    		for(var i=0;i<items.length;i++) {
    			if(items[i].data.pcode == record.data.pcode && items[i].data.pname == record.data.pname) {
    				items[i].data.pnumber = items[i].data.pnumber + 1;
    				this.saleItemView.refresh();
    				existed = true;
    				break;
    			}			
    		}
        	if(!existed) {
        		record.data.pnumber = 1;
        		record.data.pprice = record.data.buy_price;
        		this.itemsStore.add(record);
        	}
        }, this);
	},
	
	savePurchaseOrder: function() {
		SALE.Action.getPurchaseOrderInitData(function(initData){
			var billJson = initData;
			billJson["entry_date"] = new Date();
			billJson["operator"] = SALE.App.userInfo.name;
			billJson["amount"] = 0;
			
			var details = [];	
			var records = this.itemsStore.getRange();
			for(var i=0;i<records.length;i++) {
				if(records[i].data.pcode) {
					var record = records[i];		
					details[i] = record.data;
					
					billJson["amount"] += record.get('pamount');
					details[i]['index'] = i;
				}			
			}
			
			billJson["details"] = details;
			
			if(details.length > 0) {
				//show the load mask.
				SALE.Utils.showLoadMask(this.salePanel);
							
				SALE.Action.savePurchaseOrderInfo(this.saveBillSuccessHandler.createDelegate(this), billJson, 'new');
			}
		}.createDelegate(this));
	},
	
	viewPurchaseOrder: function() {
		SALE.Action.getPurchaseOrderInitData(function(initData){
			var billJson = initData;
			billJson["entry_date"] = new Date();
			billJson["operator"] = SALE.App.userInfo.name;
			billJson["amount"] = 0;
			
			var details = [];	
			var records = this.itemsStore.getRange();
			for(var i=0;i<records.length;i++) {
				if(records[i].data.pcode) {
					var record = records[i];		
					details[i] = record.data;
					
					billJson["amount"] += record.get('pamount');
					details[i]['index'] = i;
				}			
			}
			
			if(details.length > 0) {
				
				var inputView = new PurchaseOrderInputView({
					task : 'auto',
					formData: billJson,
					details: {
						details: details
					}
				});
				inputView.initlize();
				inputView.synchronizeForm();
				SALE.App.showNextOperateTabPanel(inputView.getCorePanel(), "新增销售单");
			}
		}.createDelegate(this));
	},
	
	clearItems : function() {
		this.itemsStore.removeAll();
	},
	
	saveBillSuccessHandler : function(result) {
		//hide the load mask
		SALE.Utils.hideLoadMask();
		
		Ext.MessageBox.show({
            title:'添加成功！',
            msg: '采购单添加成功！ <br/><br/>选择"继续添加"可继续添加新的采购单。',
            buttons:{"yes":"继续添加","no":"采购单查询"},
            fn: function(btn) {
				if (btn == "yes") {
					this.clearItems();
				} else if(btn == "no") {
					PurchaseOrderSearchView.showSearchPanel();
				}
			}.createDelegate(this),
			closable:false,
            icon: Ext.MessageBox.QUESTION
        });	
	},
	
	showModifyItemWin : function() {
		
		var selNode = this.saleItemView.getSelectedRecords()[0];
		this.formDataJson = selNode.data;
		
		if(!this.inputWin) {
			this.inputForm = new Ext.FormPanel({
				margins: '10 0 5 5',
				bodyStyle : 'background-color: transparent;padding:8px 8px 2px;',
				border : false,
				labelWidth: 60,
				buttonAlign: 'center',
				defaultType: 'textfield',
				
				items:  [{
			        xtype:'fieldset',
					autoHeight:true,
					layout:'form',
					items: [{
						xtype: 'displayfield',
						fieldLabel: '商品编号',
						name: 'pcode',
						anchor: '95%'
					}, {
						xtype: 'displayfield',
						fieldLabel: '商品名称',
						name: 'pname',
						anchor: '100%'
					}, {
						xtype: 'numberfield',
						fieldLabel: '数量',
						name: 'pnumber',
						anchor: '65%'
					}, {
						xtype: 'numberfield',
						fieldLabel: '单价',
						name: 'pprice',
						anchor: '65%'
					}, {
						xtype: 'displayfield',
						fieldLabel: '金额',
						name: 'pamount',
						anchor: '95%'
					}]
				}],
				
				buttons: [{
                    text: '修改',
                    handler: function(){
						this.synchronizeJson();
						this.inputWin.hide();
                    }.createDelegate(this)
                }]
			});
			
			this.inputWin = new Ext.Window({
		 		
		 		title: '修改商品采购信息',
				closable: true,	
				collapsible  : true,
				width: 400,
				height: 238,
				plain: true,
				layout: 'fit',
				closeAction :'hide',
					
				items: this.inputForm,
					
				listeners: {
					'show': function() {
						this.synchronizeForm();			
					}.createDelegate(this),
						
					'hide': function() {							
						this.modifyItemInfo();
						this.clearForm();
					}.createDelegate(this)
		 		}
			});			
		}
		
		this.inputWin.show();
	},

	modifyItemInfo: function() {
		var items = this.itemsStore.getRange();
    	var existed = false;
		for(var i=0;i<items.length;i++) {
			if(items[i].data.pcode == this.formDataJson.pcode && items[i].data.pname == this.formDataJson.pname) {
				items[i].data.pnumber = this.formDataJson.pnumber;
				items[i].data.pprice = this.formDataJson.pprice;
				items[i].data.pamount = this.formDataJson.pamount;
				this.saleItemView.refresh();
				break;
			}			
		}
	}
});

DragOrderView.showSalePanel = function(){
	var  storageView = new DragOrderView();
	
	SALE.App.showOperateTabPanel(storageView.getCorePanel(), "商品采购");
}